package com.cloudfast.manager.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.cloudfast.manager.WordManager;
import com.cloudfast.utils.word.MergeDoc;
import com.cloudfast.utils.word.TemplateParams;
import com.cloudfast.utils.word.WordImage;
import com.cloudfast.utils.word.WordTextUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;

/**
 * word 操作类
 *
 * @author liuyw
 */
public class WordManagerImpl extends BaseManagerImpl implements WordManager {
    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    @Override
    public byte[] merge(String fileWordNames) {
        String[] fileNames = fileWordNames.split(",");
        Document finalFileDoc = null;
        for (int i = 0; i < fileNames.length; i++) {
            String filePath = fileNames[i];
            String[] sftpFileInfo = filePath.split("/");
            String fileName = sftpFileInfo[sftpFileInfo.length - 1];
            if (fileName.endsWith(".doc") || fileName.endsWith(".docx") || fileName.endsWith(".pdf")) {
                if (finalFileDoc == null) {
                    finalFileDoc = new Document(filePath);
                } else {
                    finalFileDoc.insertTextFromFile(filePath, FileFormat.Docx_2013);
                }
            }
        }
        if (finalFileDoc != null) {
            String newFilePath = this.localStoragePath(System.currentTimeMillis() + ".docx");
            finalFileDoc.saveToFile(newFilePath, FileFormat.Docx_2013);
            return fileToByte(newFilePath);
        }
        return null;
    }

    @Override
    public byte[] replace(String target, Map<String, Object> params) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            Object value = entry.getValue();
            if (value instanceof WordImage) {
                WordImage pic = (WordImage) value;
                String picContent = pic.getFilePath();
                if (StringUtils.isNotEmpty(picContent)) {
                    if (pic.isRemote()) {
                        pic.setImageByte(pic.getImageByte());
                    } else {
                        pic.setImageByte(this.fileToByte(picContent));
                    }
                } else {
                    params.put(entry.getKey(), "");
                }

            }
        }
        String newFilePath = this.localStoragePath(System.currentTimeMillis() + ".docx");
        new WordTextUtil().getWord(target, params, newFilePath);
        return fileToByte(newFilePath);
    }

    @Override
    public byte[] mergeAndReplace(MergeDoc mergeDoc) {
        byte[] wordByte = merge(mergeDoc.getFileNames());
        String target = this.byteToFile(System.currentTimeMillis() + ".docx", wordByte);
        byte[] replaceWordByte = replace(target, mergeDoc.getParams());
        File file = new File(target);
        file.delete();
        return replaceWordByte;
    }

    @Override
    public byte[] wordToPdf(String filePath) {
        filePath = filePath.replaceAll("\\\\", "/");
        String[] sftpFileInfo = filePath.split("/");
        String fileName = sftpFileInfo[sftpFileInfo.length - 1];
        String suffix = fileName.split("\\.")[1];
        if (suffix.equals("doc") || suffix.equals("docx")) {
            File file = new File(this.localStoragePath(filePath));
            try {
                Document document = new Document();
                document.loadFromFile(file.getAbsolutePath());
                // 保存为PDF格式
                String pdfPath = localStoragePath(file.getParent() + "/" + fileName.replace("." + suffix, ".pdf"));
                File pdfFile = new File(pdfPath);
                if (!pdfFile.getParentFile().exists()) {
                    pdfFile.getParentFile().mkdirs();
                }
                document.saveToFile(pdfPath, FileFormat.PDF);
                return fileToByte(pdfPath);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }
        }
        return null;
    }

    @Override
    public byte[] templateToWord(String templateName, TemplateParams params) {
        Configuration configuration = new Configuration(new Version("2.3.30"));
        configuration.setDefaultEncoding("utf-8");
        Writer out = null;
        try {
            if (!templateName.endsWith(".ftl")) {
                throw new RuntimeException("无法识别的模板类型");
            }
            File file = new File(localStoragePath(null) + "/" + templateName);
            configuration.setDirectoryForTemplateLoading(new File(file.getParentFile().getAbsolutePath()));
            // 获取模板
            Template template = configuration.getTemplate(file.getName());
            File outFile = new File(localStoragePath(null) + "/ftlWord/" + System.currentTimeMillis() + ".docx");
            // 如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }
            // 将模板和数据模型合并生成文件
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            // 生成文件
            template.process(params.getParams(), out);

            // 关闭流
            out.flush();

            Document finalFileDoc = new Document(outFile.getAbsolutePath());
            finalFileDoc.saveToFile(outFile.getAbsolutePath(), FileFormat.Docx_2013);
            return fileToByte(outFile.getAbsolutePath());

        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e2) {
                logger.error(e2.getMessage());
            }
        }
        return null;
    }

}
